package com.soul.server.server;

import com.soul.dubbo.api.db.UserInfoApi;
import com.soul.dubbo.api.mongo.RecommendUserApi;
import com.soul.dubbo.api.mongo.UserLikeApi;
import com.soul.dubbo.api.mongo.VisitorApi;
import com.soul.model.db.UserInfo;
import com.soul.model.mongo.RecommendUser;
import com.soul.model.mongo.UserLike;
import com.soul.model.mongo.Visitors;
import com.soul.model.vo.CountsVo;
import com.soul.model.vo.PageResult;
import com.soul.model.vo.UserInfoLiveVo;
import com.soul.model.vo.UserInfoVo;
import com.soul.server.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.joda.time.DateTime;
import org.joda.time.Years;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mdoya
 * @version 1.0
 * @description:
 */
@Slf4j
@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VisitorApi visitorApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    /**
     *  用户资料 - 读取
     * @param userID 可是陌生人访问
     * @return
     */
    public UserInfoVo find(Long userID) {
        return userInfoApi.findIdUser(userID != null ? userID : UserHolder.getUserId());
    }

    /**
     *  用户资料 - 保存(更新用户)
     * @param userInfoVo
     */
    public void updateUser(UserInfoVo userInfoVo) {
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoVo,userInfo);
        userInfo.setId(UserHolder.getUser().getId());
        userInfo.setAge(getAge(userInfoVo.getBirthday()));
        userInfoApi.updateUserId(userInfo);
    }

    /**
     * 通过年-月-日获取年龄
     * @param yearMonthDay
     * @return
     */
    private int getAge(String yearMonthDay){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date birthDay = sdf.parse(yearMonthDay);
            Years years = Years.yearsBetween(new DateTime(birthDay), DateTime.now());
            return years.getYears();
        } catch (ParseException e) {
            log.error("获取用户年龄失败!", e);
            return 0;
        }
    }

    /**
     *  type类型：互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     * @param type 类型
     * @return PageResult<UserInfoVo>
     */
    public PageResult<UserInfoLiveVo> findFriendFollowPage(String type, Long page, Long pagesize, String nickname) {
        Long currendUserId = UserHolder.getUserId();
        if (type.equals("4")){
            // 类型：4 谁看过我
            return getUserInfoLiveVoPageResult(page, pagesize, nickname, currendUserId);
        } else if (type.equals("3")){
            // 类型：3 粉丝
            return getFansPageResult(page, pagesize, nickname, currendUserId);
        } else if (type.equals("2")){
            // 类型：2 喜欢
            return getLiveVoPageResult(page, pagesize, nickname, currendUserId);
        }
            // 类型：1 互相喜欢
        return getInfoLiveVoPageResult(page, pagesize, nickname, currendUserId);
    }

    /**
     *  型：3 粉丝
     * @param page
     * @param pagesize
     * @param nickname
     * @param currendUserId
     * @return
     */
    private PageResult<UserInfoLiveVo> getFansPageResult(Long page, Long pagesize, String nickname, Long currendUserId) {
        // 1. 条件查询后用户ids
        List<Long> infoIds = null;
        if (StringUtils.isNotEmpty(nickname)){
            infoIds = findNicknameUserInfoIds(nickname, page, pagesize);
        }
        // 2. 粉丝ids
        PageResult<UserLike> userLikePageResult = userLikeApi.findFanUserLike(page, pagesize, currendUserId,infoIds);
        if (CollectionUtils.isEmpty(userLikePageResult.getItems())){
            return null;
        }
        // 3. 根据粉丝ids查询粉丝详细信息
        List<UserLike> userLikeList = userLikePageResult.getItems();
        List<Long> userLikeFanIds = userLikeList.stream().map(UserLike::getUserId).collect(Collectors.toList());
        Map<Long, UserInfo> userInfoMap = userInfoApi.findIdsUserInfoList(userLikeFanIds);
        // 4. 构建Vo数据
        List<UserInfoLiveVo> userInfoLiveVoList = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            if (userInfoMap != null){
                UserInfo userInfo = userInfoMap.get(userLike.getUserId());
                if (userInfo != null){
                    UserInfoLiveVo userInfoLiveVo = new UserInfoLiveVo();
                    BeanUtils.copyProperties(userInfo,userInfoLiveVo);
                    userInfoLiveVoList.add(userInfoLiveVo);
                }
            }
        }
        // 5. 返回数据
        return new PageResult<>(page, pagesize,Long.valueOf(userInfoLiveVoList.size()),userInfoLiveVoList);
    }

    /**
     *  类型：2 喜欢
     * @param page
     * @param pagesize
     * @param nickname
     * @param currendUserId
     * @return
     */
    private PageResult<UserInfoLiveVo> getLiveVoPageResult(Long page, Long pagesize, String nickname, Long currendUserId) {
        // 1. 条件查询用户ids(可以是喜欢的人id)
        List<Long> userInfoIds = new ArrayList<>();
        if (StringUtils.isNotEmpty(nickname)){
            userInfoIds = findNicknameUserInfoIds(nickname, page, pagesize);
        }
        // 2. 查询喜欢的人
        PageResult<UserLike> userLikePageResult = userLikeApi.findLikeUser(page, pagesize, currendUserId,userInfoIds);
        if (CollectionUtils.isEmpty(userLikePageResult.getItems())){
            return null;
        }
        // 3. 喜欢的人详细信息
        List<UserLike> userLikeList = userLikePageResult.getItems();
        List<Long> userLikeUserIds = userLikeList.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        Map<Long, UserInfo> userInfoMap = userInfoApi.findIdsUserInfoList(userLikeUserIds);
        // 4. 构造数据
        List<UserInfoLiveVo> userInfoLiveVoList = new ArrayList<>();
        for (UserLike userLike : userLikeList) {
            if (userInfoMap != null){
                UserInfo userInfo = userInfoMap.get(userLike.getLikeUserId());
                if (userInfo != null){
                    UserInfoLiveVo userInfoLiveVo = new UserInfoLiveVo();
                    BeanUtils.copyProperties(userInfo,userInfoLiveVo);
                    userInfoLiveVoList.add(userInfoLiveVo);
                }
            }
        }
        // 5. 返回数据
        return new PageResult<>(page, pagesize,Long.valueOf(userInfoLiveVoList.size()),userInfoLiveVoList);
    }

    /**
     *  // 类型：1 互相喜欢功能
     * @param page
     * @param pagesize
     * @param nickname
     * @param currendUserId
     * @return
     */
    private PageResult<UserInfoLiveVo> getInfoLiveVoPageResult(Long page, Long pagesize, String nickname, Long currendUserId) {
        // 1. 条件查询用户ids
        List<Long> userInfoIdsList = findNicknameUserInfoIds(nickname,page,pagesize);
        if (CollectionUtils.isEmpty(userInfoIdsList)) return null;
        // 2. 查询相互喜欢
        PageResult<UserLike> userLikePageResult = userLikeApi.findUserAlreadyLovePage(page, pagesize, currendUserId,userInfoIdsList);
        if (CollectionUtils.isEmpty(userLikePageResult.getItems())){
            return null;
        }
        List<UserLike> userLikeList = userLikePageResult.getItems();
        // 3. 相互喜欢用户ids
        List<Long> userLikeUserIds = userLikeList.stream().map(UserLike::getUserId).collect(Collectors.toList());
        UserInfo userInfoCondition = new UserInfo();
        userInfoCondition.setNickname(nickname);
        // 4. 当前用户喜欢的用户详细信息
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIdsAndCondition(userLikeUserIds,userInfoCondition);
        List<UserInfoLiveVo> userInfoLiveVoList = new ArrayList<>();
        // 5. 构建UserInfoLiveVo数据
        for (UserLike userLike : userLikeList) {
            if (userInfoMap != null){
                UserInfo userInfo = userInfoMap.get(userLike.getUserId());
                if (userInfo != null){
                    UserInfoLiveVo userInfoLiveVo = new UserInfoLiveVo();
                    BeanUtils.copyProperties(userInfo,userInfoLiveVo);
                    userInfoLiveVoList.add(userInfoLiveVo);
                }
            }
        }
        // 6. 返回数据
        return new PageResult<>(page, pagesize,userLikePageResult.getCounts(),userInfoLiveVoList);
    }

    /**
     *  根据昵称查询用户ids
     * @param nickname
     * @return
     */
    private List<Long> findNicknameUserInfoIds(String nickname,Long page,Long pagesize) {
        List<Long> userInfoIdsList = new ArrayList<>();
        if (StringUtils.isNotEmpty(nickname)){
            UserInfo userInfo = new UserInfo();
            userInfo.setNickname(nickname);
            List<UserInfo> userInfoList = userInfoApi.findNicknameUser(userInfo,page,pagesize);
            if (CollectionUtils.isEmpty(userInfoList)){
                return null;
            }
            userInfoIdsList = userInfoList.stream().map(UserInfo::getId).collect(Collectors.toList());
        }
        return userInfoIdsList;
    }

    /**
     *  类型：4 谁看过我功能
     * @param page
     * @param pagesize
     * @param nickname
     * @param currendUserId
     * @return
     */
    private PageResult<UserInfoLiveVo> getUserInfoLiveVoPageResult(Long page, Long pagesize, String nickname, Long currendUserId) {
        // 1. 查询访问者ids
        PageResult<Visitors> visitorsPageResult = visitorApi.findFriendFollowPage(currendUserId, page, pagesize);
        if (CollectionUtils.isEmpty(visitorsPageResult.getItems())){
            return null;
        }
        List<Visitors> visitorsList = visitorsPageResult.getItems();
        List<Long> visitorsIdsList = visitorsList.stream().map(Visitors::getVisitorUserId).collect(Collectors.toList());

        UserInfo userInfoCondition = new UserInfo();
        userInfoCondition.setNickname(nickname);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIdsAndCondition(visitorsIdsList, userInfoCondition);
        List<UserInfoLiveVo> userInfoVoList = new ArrayList<>();
        for (Visitors visitors : visitorsList) {
            if (userInfoMap != null){
                UserInfo userInfo = userInfoMap.get(visitors.getVisitorUserId());
                if (userInfo != null){
                    UserInfoLiveVo userInfoLiveVo = new UserInfoLiveVo();
                    BeanUtils.copyProperties(userInfo,userInfoLiveVo);
                    if (!String.valueOf(visitors.getUserId()).equals(String.valueOf(userInfo.getId()))){
                        RecommendUser recommendUser = recommendUserApi.findUserMatchRate(visitors.getUserId(),userInfo.getId());
                        if (recommendUser != null){
                            userInfoLiveVo.setMatchRate(recommendUser.getScore().intValue()); // 匹配度
                        }
                    }
                    userInfoVoList.add(userInfoLiveVo);
                }
            }
        }
        return new PageResult<>(page, pagesize,visitorsPageResult.getCounts(),userInfoVoList);
    }

    /**
     *  互相喜欢，喜欢，粉丝 - 统计当前用户
     * @return CountsVo
     */
    public CountsVo counts() {
        Long currendUserId = UserHolder.getUserId();
        CountsVo countsVo = new CountsVo();
        // 喜欢 自己关注别人
        countsVo.setLoveCount(userLikeApi.findLoveCount(currendUserId));
        // 粉丝 别人关注
        countsVo.setFanCount(userLikeApi.findFanCount(currendUserId));
        // 互相喜欢
        countsVo.setEachLoveCount(userLikeApi.findEachLoveCount(currendUserId));
        return countsVo;
    }
}